package com.example.kuaizu.interceptors;

import com.example.kuaizu.utils.JwtUtils;
import com.example.kuaizu.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


import kuaizu.common.exception.MassageException;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/*拦截器对象*/
@Log4j2
@Component//加载到spring容器中
public class LoginInterceptor implements HandlerInterceptor {


    //请求来是执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        //拦截请求 做令牌验证
        String token = request.getHeader("Authorization");
        log.info("当前请求的 URI: {} token的值:{}", requestURI,token);
        //System.out.println("token的值--->" + token);
        if ("true".equals(request.getHeader("H1"))) {
            log.info("北荣登录");
            return true;
        }
        try {
            if(null == token){
                //设置http响应状态码
                response.setStatus(401);
                //设置相应数据的编码格式
                response.setContentType("text/html;charset=utf-8");
                //响应数据
                response.getWriter().write("令牌解析失败,重新登陆");
                return false;
            }
            //不正确token会报错
            Map<String, Object> stringtoken = JwtUtils.parseToken(token);
//            System.err.println(stringtoken);
//            log.info("stringtoken的值{}" , stringtoken);
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(stringtoken);
            //放行请求
            return true;
        } catch (Exception e) {
            log.error("令牌解析失败{}",e);
            //设置http响应状态码
            response.setStatus(401);
            //设置相应数据的编码格式
            response.setContentType("text/html;charset=utf-8");
            //响应数据
            response.getWriter().write("令牌解析失败,重新登陆");
            return true;//不放行代码
        }
    }

    //请求结束后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}



